using System;
using System.Collections;
using Db4objects.Db4o;
using Db4objects.Db4o.Query;

namespace Curriculum.Utiles
{
	/// <summary>
	/// Summary description for IdGenerator.
	/// </summary>
	public class IdGenerator
	{		
		public IdGenerator()
		{

		}	

		public static string GetNextId(Type tipo, IObjectContainer container)
		{
			if (container != null)
			{
				string tipoBuscado = tipo.ToString();
				ParClaseId parClaseId;
			
				IQuery q = container.Query();
			
				q.Constrain(typeof(ParClaseId));
				q.Descend("_clase").Constrain(tipoBuscado);
			
				IObjectSet result = q.Execute();

				if (result.Count > 0)
				{
					parClaseId = result.Next() as ParClaseId;
					parClaseId.Id++;				
				}
				else
				{
					parClaseId = new ParClaseId();
					parClaseId.Clase = tipoBuscado;
					parClaseId.Id = 1;				
				}

				container.Set(parClaseId);
			
				return parClaseId.Id.ToString();
			}
			else
			{
				throw(new Exception("el container no debe ser nulo"));
			}
		}
	}

	internal class ParClaseId
	{
		private string _clase;
		private int _id;

		public string Clase
		{
			get { return _clase; }
			set { _clase = value; }
		}

		public int Id
		{
			get { return _id; }
			set { _id = value; }
		}
	}
}


